#include <webby/fastcgi.hxx>
#include <memory.h>

using namespace webby;

void
FastCGI::makeBeginRequest()
{
	mType = BEGIN_REQUEST;
	mRole = RESPONDER;

	memset( mBuffer, 0, 1000 );
	mLength = 0;
	mBuffer[0] = mVersion;
	mBuffer[1] = (unsigned char)mType;
	mBuffer[2] = 0;
	mBuffer[3] = mID & 0xff;
	mBuffer[4] = 0;
	mBuffer[5] = 8;
	mBuffer[6] = 0;
	mBuffer[7] = 0;
	mBuffer[8] = 0;
	mBuffer[9] = (unsigned char)mRole;
//	mBuffer[10] = 1;
}

void
FastCGI::encodeParam( const std::string &name, const std::string &value)
{
	mType = PARAMS;
	memset( mBuffer, 0, 1000 );

	mBuffer[0] = mVersion;
	mBuffer[1] = (unsigned char)mType;
	mBuffer[2] = 0;
	mBuffer[3] = mID & 0xff;
	mBuffer[4] = 0;
	mBuffer[5] = 8;
	mBuffer[6] = 0;
	mBuffer[7] = 0;
	mBuffer[8] = name.size();
	mBuffer[9] = value.size();

	unsigned int pos = 10;
	for (unsigned int i = 0; i < name.size(); ++i)
	{
		mBuffer[pos] = name[i];
		pos++;
	}

	for (unsigned int i = 0; i < value.size(); ++i)
	{
		mBuffer[pos] = value[i];
		pos++;
	}

	mBuffer[5] = 2 + name.size() + value.size();
}

void
FastCGI::makeStdIn()
{
	mType = STDIN;
	memset( mBuffer, 0, 1000 );

	mBuffer[0] = mVersion;
	mBuffer[1] = (unsigned char)mType;
	mBuffer[2] = 0;
	mBuffer[3] = mID & 0xff;
	mBuffer[4] = 0;
	mBuffer[5] = 0;
	mBuffer[6] = 0;
	mBuffer[7] = 0;
}
